package com.shop.cart.controller;

import com.netflix.discovery.converters.Auto;
import com.shop.cart.entity.CartItem;
import com.shop.cart.entity.CartItemVO;
import com.shop.cart.service.CartService;
import com.shop.common.constant.CookieConstant;
import com.shop.common.constant.RedisConstant;
import com.shop.common.entity.CommonResult;
import com.shop.common.util.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-11-03
 */
@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {


    @Autowired
    CartService cartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    HttpServletResponse response;

    @GetMapping("/merge")
    public CommonResult merge(@CookieValue(name = "cart_token", required = false) String cookieCartToken,
                            @CookieValue(name = "login_token", required = false) String loginToken) {
                            //HttpServletResponse response) {

        //1.得到两个购物车
        //未登录状态下的购物车
        String redis_unLogin = StrUtils.getRedisKey(RedisConstant.CART_TOKEN, cookieCartToken);
        List<CartItem> unLoginCart = (List<CartItem>) redisTemplate.opsForValue().get(redis_unLogin);
        //已登录状态下的购物车
        //通过login_token得到用户ID
        String userId = cartService.getUserId(loginToken);
        String redis_login = StrUtils.getRedisKey(RedisConstant.CART_TOKEN, userId);
        List<CartItem> loginCart = (List<CartItem>) redisTemplate.opsForValue().get(redis_login);

        log.info("---未登录状态的购物车:{}", unLoginCart);
        log.info("===已登录状态的购物车:{}", loginCart);

        if (unLoginCart != null && unLoginCart.size() > 0) {
            //未登录购物车有数据
            if (loginCart != null && loginCart.size() > 0) {
                //已登录购物车有数据
                Map<Long, CartItem> map = new HashMap<>();
                for (CartItem cartItem : loginCart) {
                    map.put(cartItem.getPid(), cartItem);
                }
                //把未登录的合并到已登录的
                for (CartItem item : unLoginCart) {
                    if (map.containsKey(item.getPid())) {
                        //有，未登录购物车的商品，已登录购物车中有
                        CartItem loginItem = map.get(item.getPid());
                        //更新数量
                        loginItem.setNum(loginItem.getNum() + item.getNum());
                        //更新时间
                        if (item.getUpdateTime().getTime() > loginItem.getUpdateTime().getTime()) {
                            loginItem.setUpdateTime(item.getUpdateTime());
                        }
                    } else {
                        //没有，未登录购物车的商品，已登录购物车中没有
                        map.put(item.getPid(), item);
                    }
                }

                loginCart = new ArrayList<>(map.values());

                redisTemplate.opsForValue().set(redis_login, loginCart);
            } else {
                //已登录购物车没有数据
                redisTemplate.opsForValue().set(redis_login, unLoginCart);
            }
            //删除未登录购物车的cookie
            //Cookie cookie = new Cookie(CookieConstant.CART_TOKEN, "");
            //cookie.setPath("/");
            //cookie.setMaxAge(0);
            //response.addCookie(cookie);

            //删除未登录购物车的redis中的数据
            redisTemplate.delete(redis_unLogin);

        }

        loginCart = (List<CartItem>) redisTemplate.opsForValue().get(redis_login);

        return new CommonResult("合并成功", loginCart);
    }

    /**
     * 展示购物车
     *
     * @param cookieCartToken
     * @return
     */
    @GetMapping("/show")
    public CommonResult show(@CookieValue(name = "cart_token", required = false) String cookieCartToken,
                             @CookieValue(name = "login_token", required = false) String loginToken) {

        //1.判断是否登录
        if (!StringUtils.isBlank(loginToken)) {
            //有loginToken，redis中有没有对应的用户数据是不是不确定
            //2.根据loginToken去redis查询用户信息
            String userId = cartService.getUserId(loginToken);
            //2.1 如果有，则才是登录成功的
            if (!StringUtils.isBlank(userId)) {
                //登录成功
                List<CartItemVO> cart = cartService.show(userId);
                return new CommonResult(true, "已登录的购物车", cart);
            }
        }

        List<CartItemVO> cart = cartService.show(cookieCartToken);
        return new CommonResult("未登录的购物车", cart);

    }


    /**
     * 加入购物车
     *
     * @param pid
     * @param num
     * @param cookieCartToken
     * @param response
     * @return
     */
    @GetMapping("/add")
    public CommonResult add(@RequestParam(name = "pid", required = true) Long pid,
                            @RequestParam(name = "num", required = true) Integer num,
                            @CookieValue(name = "cart_token", required = false) String cookieCartToken,
                            @CookieValue(name = "login_token", required = false) String loginToken) {
                            //HttpServletResponse response

        //1.判断是否登录
        if (!StringUtils.isBlank(loginToken)) {
            //有loginToken，redis中有没有对应的用户数据是不是不确定
            //2.根据loginToken去redis查询用户信息
            String userId = cartService.getUserId(loginToken);
            //2.1 如果有，则才是登录成功的
            if (!StringUtils.isBlank(userId)) {
                //登录成功
                //直接返回购物车
                return cartService.add(pid, num, userId);
            }
        }

        //2.2 如果没有，还是未登录
        try {
            //有没有cookie
            if (StringUtils.isBlank(cookieCartToken)) {
                //没有cookie，代表第一次加入购物车
                cookieCartToken = StrUtils.uuidToken();
                Cookie cookie = new Cookie(CookieConstant.CART_TOKEN, cookieCartToken);
                cookie.setPath("/");
                //向前台发送一个cookie
                response.addCookie(cookie);
            }
            //
            return cartService.add(pid, num, cookieCartToken);
            //
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(false, "加入购物车失败", e.getMessage());
        }

    }


//    /**
//     * 加入购物车
//     * @param pid
//     * @param num
//     * @param cookieCartToken
//     * @param response
//     * @return
//     */
//    @GetMapping("/add")
//    public CommonResult add(@RequestParam(name = "pid", required = true) Long pid,
//                            @RequestParam(name = "num", required = true) Integer num,
//                            @CookieValue(name = "cart_token", required = false) String cookieCartToken,
//                            HttpServletResponse response){
//
//        try {
//            //有没有cookie
//            if(StringUtils.isBlank(cookieCartToken)) {
//                //没有cookie，代表第一次加入购物车
//                cookieCartToken = StrUtils.uuidToken();
//                Cookie cookie = new Cookie(CookieConstant.CART_TOKEN, cookieCartToken);
//                cookie.setPath("/");
//                //向前台发送一个cookie
//                response.addCookie(cookie);
//            }
//
//            return cartService.add(pid,num, cookieCartToken);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new CommonResult(false, "加入购物车失败", e.getMessage());
//        }
//
//    }
//
//


}
